<?php
/**
 * @author	yuchen
 * @since	20170624
 * @version	1.0
 * @package	管理员
 */
namespace app\manager\controller;

use app\manager\model\admin;

class Index {

	private $string = 'abcdfghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	
	public function index() {
		echo 'admin';
	}
	// 注册后台用户
	public function insert() {
		$name		= input('request.name');
		$add_time	= time();

		$admin		= new Admin;
		$admin_info	= $admin->where('name', $name)->find();
		if (!empty($admin_info)) {
			return json_success('用户名已存在', 501);
		}

		// 生成密码
		$pwd_arr	= $this->pwdToMd5('111111');
		// 插入数据
		$admin->data([
			'name'		=> $name,
			'password'	=> $pwd_arr['password'],
			'salt'		=> $pwd_arr['salt'],
			'add_time'	=> $add_time
		]);
		$admin->save();

		return json_success($admin->id);
	}
	// 修改密码
	public function changePwd() {
		$admin_id	= input('admin_id');
		$new_pwd	= input('new_pwd');

		$pwd_arr	= $this->pwdToMd5($new_pwd);

		$admin		= new Admin;
		$admin->data([
			'id'		=> $admin_id,
			'password'	=> $pwd_arr['password'],
			'salt'		=> $pwd_arr['salt']
		]);
		$res = $admin->isUpdate(true)->save();
		
		return json_success($res);
	}
	// 密码加密处理
	private function pwdToMd5($pwd = '', $salt = '') {
		// 获取字典长度
		$str_len = strlen($this->string) - 1;
		// 判断密码令牌是否为空
		if (empty($salt)) {
			$salt = '';
			for ($i = 0; $i < 6; $i++) { 
				$salt .= substr($this->string, mt_rand(0, $str_len), 1);
			}
		}
		// 生成加密的密码
		$md5_pwd = md5(md5($pwd) . ' + ' . md5($salt));
		$result  = array(
			'password'	=> $md5_pwd,
			'salt'		=> $salt
		);
		return $result;
	}
	// 管理员登录
	public function adminLogin() {
		$name		= input('name');
		$pwd		= input('pwd');

		if (!empty($name) && !empty($pwd)) {
			$admin		= new Admin;
			$admin_info	= $admin->where('name', $name)->find();
			
			if (empty($admin_info)) {
				return json_success('用户名不存在', 502);
			}
			if ($admin_info['status'] != 1) {
				return json_success('用户被锁定', 503);
			}

			$md5_pwd	= $this->pwdToMd5($pwd, $admin_info['salt']);
			if ($md5_pwd['password'] !== $admin_info['password']) {
				return json_success('帐号或密码不正确', 505);
			}

			$admin->data([
				'id'		=> $admin_info['id'],
				'login_time'=> time(),
				'login_ip'	=> request()->ip()
			]);
			$res = $admin->isUpdate(true)->save();
			trace('管理员: ' . $admin_info['id'] . ', 登录成功', 'info');

			session('admin_id', $admin_info['id']);

			return json_success();
		} else {
			return json_success('用户名和密码不能为空', 504);
		}
	}
	// 管理员退出登录
	public function adminLogout() {
		$admin_id	= session('admin_id');
		// 记录日志
		trace('管理员: ' . $admin_id . ', 退出登录', 'info');
		
		session('admin_id', null);
		return json_success();
	}
}
